#include <algorithm>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    string arrangeWords(string text) {
        vector<pair<string, int>> store;
        int start = 0;
        for (int i = 0; i < text.size(); i++) {
            text[i] = tolower(text[i]);
            if (text[i] == ' ') {
                store.emplace_back(make_pair(text.substr(start, i - start), store.size()));
                start = i + 1;
            }
        }
        store.emplace_back(make_pair(text.substr(start, text.size() - start), store.size()));
        sort(store.begin(), store.end(), [] (pair<string, int>& a, pair<string, int>& b) {
            if (a.first.size() == b.first.size()) {
                return a.second < b.second;
            } else {
                return a.first.size() < b.first.size();
            }
        });
        string ans;
        for (pair<string, int>& it : store) {
            ans += it.first + " ";
        }
        ans.pop_back();
        ans[0] = toupper(ans[0]);
        return ans;
    }
};